package com.zhugang.week05;

/**
 * @program algorithms
 * @description: bSearch
 * @author: chanzhugang
 * @create: 2022/07/03 23:47
 */
public class BSearch {

    public static void main(String[] args) {
        BSearch bSearch = new BSearch();
        int[] a = new int[]{1, 2, 3, 4, 5};
        int index = bSearch.bSearch(a, a.length, 3);
        System.out.println(index);
    }

    /**
     * 二分查找（非递归实现）
     *
     * @param a
     * @param n
     * @param value
     * @return
     */
    public int bSearch(int[] a, int n, int value) {
        // 有序数组
        int low = 0;
        int high = n - 1;
        while (low <= high) {
            // 折半找中间下标
            int mid = (low + high) / 2;
            if (a[mid] == value) {
                return mid;
            } else if (a[mid] < value) {
                low = mid + 1;
            } else {
                high = mid - 1;
            }
        }
        return -1;
    }
}